<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 18px">
      <el-breadcrumb-item :to="{ path: '/' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item >类别列表</el-breadcrumb-item>
      <el-breadcrumb-item v-for="item in history"><span>{{ item.name }}</span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!--用户列表-->
    <div style="float: right;position: relative;margin-bottom: 20px">
      <el-input placeholder="请输入类别名称" v-model="categoryNameSearch">
        <el-button slot="append" icon="el-icon-search" @click="categorySearch()" style="color: #0095d7">
          搜索
        </el-button>
      </el-input>
    </div>
    <!--添加用户信息-->
    <div style="margin-left: 20px">
      <el-button type="primary" icon="el-icon-plus" @click="addCategory()">
        类别名称
      </el-button>
      <el-button type="primary" icon="el-icon-user-solid" @click="allCategory()">
        全部类别
      </el-button>
    </div>

    <el-table
        :data="categoryArr"
        style="width: 100%;margin:0 20px 20px 20px" border>
      <el-table-column type="index" label="" width="50" align="center"></el-table-column>
      <el-table-column prop="id" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="name" label="类别名称" align="center"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center"></el-table-column>
      <el-table-column prop="sort" label="排序" width="80" align="center"></el-table-column>
      <el-table-column prop="created" label="创建时间" align="center"></el-table-column>
      <el-table-column label="子级类别" width="100" align="center">
        <template slot-scope="scope">
          <el-button size="mini" :disabled="scope.row.isParent == 0"
                     @click="showSubCategories(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" width="80" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="changeEnable(scope.row)"
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#AAAAAA">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="socpe">
          <el-button
              size="mini"
              @click="userUpdate(socpe.row)"
              type="success">修改
          </el-button>
          <el-popconfirm
              title="您确定删除此类别吗?"
              @confirm="categoryDelete(socpe.$index, socpe.row)">
            <el-button
                slot="reference" size="mini"
                type="danger">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--用户列表结束-->
    <el-button style="margin-top: 10px; float: right;"
               v-if="currentDepth != 1" @click="goBack()">返回
    </el-button>

    <el-dialog title="添加类别" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" :rules="rules">
        <el-form-item label="父级类别" prop="parentId">
          <el-input v-model="ruleForm.parentId" placeholder="请输入父级类别的id，一级类别请填0"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="ruleForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-switch
              v-model="ruleForm.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

export default {
  data() {
    return {
      categoryNameSearch: '',
      history: [],
      currentDepth: 1,
      currentParentId: 0,
      categoryArr: [],
      ruleForm: {
        parentId: '',
        name: '',
        remark: '',
        sort: '',
        enable:'',
        created:''
      },
      rules: {
        parentId: [
          {required: true, message: '请输入父级类别id，一级类别请填0', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入类别名称', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
        ],
        sort: [
          {pattern: /^(\d{1}|[1-9]{1}[0-9]?)$/, message: '排序序号必须是 0~99 之间的数字', trigger: 'blur'}
        ]
      },
      dialogFormVisible: false,
      formLabelWidth: '120px'
    };
  },
  methods: {
    goBack() {
      let parentCategory = this.history[--this.currentDepth - 1];
      this.history.pop();
      this.currentParentId = parentCategory.parentId;
      this.loadAllCategoryInfo();
    },
    showSubCategories(category) {
      this.history[this.currentDepth - 1] = category;
      this.currentParentId = category.id;
      this.currentDepth++;
      this.loadAllCategoryInfo();
    },
    loadAllCategoryInfo() {
      let url = 'http://localhost:8080/categories/list?parentId=' + this.currentParentId;
      console.log('url>>>' + url)
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        this.categoryArr = response.data.data;
      })
    },
    addCategory() {
      this.dialogFormVisible = true;
    },
    submitForm(formName) {
      let url = 'http://localhost:8080/categories/add-new';
      console.log('url = ' + url);
      let formData = this.qs.stringify(this.ruleForm);
      console.log('formData = ' + formData);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        console.log('服务器端响应的结果：' + response);
        console.log(response);
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: '添加成功！',
            type: 'success'
          });
          this.ruleForm = {};
        } else {
          console.log(responseBody.message);
          this.$message.error(responseBody.message);
        }
      });
    },
    submitEdit() {
      this.loadAllCategoryInfo();
      this.dialogFormVisible = false;
    },
    changeEnable(category) {
      let enableText = ['禁用', '启用'];
      let url = 'http://localhost:8080/categories/' + category.id;
      if (category.enable == 1) {
        url += '/enable';
      } else {
        url += '/disable';
      }
      console.log("category>>>"+category.enable)
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          let message = '【' + category.name + '】的启用状态改为【' + enableText[category.enable] + '】成功！';
          this.$message({
            message: message,
            type: 'success'
          });
        } else {
          this.$message.error(responseBody.message);
        }
        if (responseBody.state == 40400) {
          this.loadAllCategoryInfo();
        }
      });
    },
    categoryDelete(key, category) {
      let url = 'http://localhost:8080/categories/' + category.id + '/delete'
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        if (response.data.state == 20000) {
          this.$message.success("删除成功");
          this.loadAllCategoryInfo();
        } else {
          this.$message.error(response.data.message);
          this.loadAllCategoryInfo();
        }
      })
    },
    categorySearch() {
      if (this.categoryNameSearch == '') {
        this.$message.error("类别名不能为空");
        return;
      }
      let url = 'http://localhost:8080/categories/search?categoryName=' + this.categoryNameSearch;
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
            if ( response.data.state==20000){
              this.categoryArr = response.data.data;
              this.categoryNameSearch = '';
            }else {
              this.$message.error(response.data.message)
            }
      })
    },
    allCategory(){
      this.loadAllCategoryInfo();
    },




    /*用户管理之修改用户信息*/
    userUpdate(user) {
      location.href = "/sys-admin/temp/user/list/update?id=" + user.id;
    },
  },
  mounted() {
    this.loadAllCategoryInfo();
  }
}
</script>